package com.penjin.android.activity.kaoqin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.activity.secretary.Data;
import com.penjin.android.adapter.ListAdapterKaoqinTiaoxiu;
import com.penjin.android.adapter.ListViewAdapter;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.KaoqinDepartment;
import com.penjin.android.domain.KaoqinLeaveData;
import com.penjin.android.domain.KaoqinPersonData;
import com.penjin.android.domain.KaoqinTiaoxiuData;
import com.penjin.android.domain.PenjinDepartment;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by fengjw on 2016/4/9.
 */
public class NoSignKaoqinActivity extends Activity implements View.OnClickListener {

    private CustomProgressDialog progressDialog;
    DatePickerDialog datePicker;
    com.wdullaer.materialdatetimepicker.date.DatePickerDialog.OnDateSetListener onDateSetListener;
    TextView startDate;
    //
    PenjinUser user;
    public List<KaoqinPersonData> datas=new ArrayList<KaoqinPersonData>();
    public List<KaoqinDepartment> departments=new ArrayList<>();

    private Context context=this;


    private String title;
    private String url;
    private String userId;
    private String companyId;
    private String time;
    private TitleBarView titleBarView;
    private TextView centerView;

    private ListView lv;
    private ListViewAdapter listViewAdapter;

    private ListAdapterKaoqinTiaoxiu listAdapterKaoqinTiaoxiu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_kaoqin_nosign);

        Intent intent=getIntent();
        title=intent.getStringExtra("title");

        initData();

        initTitleBar();
    }




    public void initData(){
        startDate = (TextView)findViewById(R.id.kapqin_son_date_image);
        startDate.setOnClickListener(this);
        progressDialog = CustomProgressDialog.createDialog(this);

        this.onDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                startDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth );
                time = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                Log.d("fengjw", "time1 :" + time);
            }
        };

        Date date = new Date();
        int year = date.getYear() + 1900;
        int month = date.getMonth();
        int day = date.getDate();
        datePicker = DatePickerDialog.newInstance(this.onDateSetListener, year, month, day);
        Log.d("fengjw","Date : "+ datePicker);

        user = UserService.getInstance(this.getApplicationContext()).getCurrentUser();
        if (user == null) {
            Toast.makeText(this, "用户尚未登陆！", Toast.LENGTH_SHORT).show();
            finish();
        }
        userId=user.getPhone();
        companyId=user.getCompanyId();
        Log.d("fengjw",userId+"   "+companyId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        time = simpleDateFormat.format(curDate);
        startDate.setText(time);

        if(title.equals("缺勤记录")) {
            //Log.d("fengjw","缺勤记录");
            url= HttpConstants.HOST + HttpConstants.KaoqinNoSignIn;
            hpptNoSignIn();
        }else if(title.equals("请假/调休")){
            //Log.d("fengjw","请假/调休");
            url = HttpConstants.HOST + HttpConstants.KaoqinQingJiaAndTiaoXiu;
            httpTiaoXiu();
        }else if(title.equals("值班/加班")){
            url = HttpConstants.HOST + HttpConstants.KaoqinZhiBanAndJiaBan;
            //Log.d("fengjw","值班/加班");
            httpJiaBan();
        }else {
            Log.d("fengjw","no title");
        }



    }
    //NoSignIn
    private void hpptNoSignIn(){
        if(datas.isEmpty()){

            HttpService httpService= HttpService.getInstance(this);
            if(NetUtils.hasNetwork(this)){
                try{

                    RequestParams requestParams=new RequestParams();
                    requestParams.put("companyId",companyId);
                    requestParams.put("userName",userId);

                    requestParams.put("date",time);
                    //requestParams.put("date","2016-04-08");
                    //Log.d("fengjw","DATA:"+userId+" "+companyId);

                    //url

                    httpService.postRequest(this, url, requestParams, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            if (s == null) {
                                Toast.makeText(context, "服务器内部错误", Toast.LENGTH_SHORT).show();
                            } else {
                                System.out.println(s);
                                Toast.makeText(context, "资源路径出错", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            try {
                                JSONObject jo = new JSONObject(s);

                                if (jo.getBoolean("result")) {
                                    List<PenjinDepartment> departmentList = new ArrayList();
                                    List<List<KaoqinPersonData>> staffLists = new ArrayList<>();

                                    JSONArray ja = jo.getJSONArray("data");
                                    //Log.d("fengjw","data:   "+ja.toString()) ;

                                    JSONObject entity;

                                    if (ja != null && ja.length() > 0) {

                                        for( int j = 0 ; j < ja.length() ; j++){
                                            entity = ja.getJSONObject(j) ;

                                            PenjinDepartment department = new PenjinDepartment();
                                            department.setDepartmentName(entity.optString("department"));

                                            //Log.d("fengjw","deparment:"+department) ;

                                            JSONArray persons = entity.optJSONArray("staffs");
                                            if(persons.length()>0){
                                                //添加部门
                                                departmentList.add(department);

                                                //添加员工
                                                List<KaoqinPersonData> staffList = new ArrayList<>();
                                                department.setDepartmentStaffNum(persons.length());
                                                //Log.d("fengjw","person count:  "+persons.length());

                                                JSONObject person;
                                                for(int  m = 0; m < persons.length(); m ++){
                                                    person = persons.optJSONObject(m);

                                                    KaoqinPersonData staff = new  KaoqinPersonData();
                                                    staff.setName(person.getString("name"));
                                                    staff.setCount(person.getString("count"));
                                                    staff.setHeadUrl(person.getString("headUrl"));

//                                                    Log.d("fengjw","staff :"+person.getString("name") +
//                                                            "   "+person.getString("count") + " " +
//                                                                    "   " + person.getString("headUrl"));

                                                    staffList.add(staff);
                                                 //   Log.d("fengjw","staffList:  "+staffList);
                                                }
                                                staffLists.add(staffList);

                                               // Log.d("fengjw","staffLists: "+staffLists);
                                            }
                                        }

                                        lv = (ListView) findViewById(R.id.lv);
                                        listViewAdapter = new ListViewAdapter(NoSignKaoqinActivity.this);
                                        //Log.d("fengjw","1");
                                        listViewAdapter.setData(departmentList, staffLists);
                                        //Log.d("fengjw","2");
                                        listViewAdapter.notifyDataSetChanged();
                                        lv.setAdapter(listViewAdapter);

                                        //Log.d("fengjw","3");

                                    }else {
                                        Toast.makeText(context, "暂无数据信息", Toast.LENGTH_SHORT).show();
                                    }
                                }else{
                                    Log.v("fengjw","no!");
                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                Toast.makeText(this, "网络不可用...", Toast.LENGTH_SHORT).show();
            }

        }
    }

    //TiaoXiu
    private void httpTiaoXiu(){
        if(datas.isEmpty()){

            HttpService httpService= HttpService.getInstance(this);
            if(NetUtils.hasNetwork(this)){
                try{

                    RequestParams requestParams=new RequestParams();
                    requestParams.put("companyId",companyId);
                    requestParams.put("userName",userId);

                    requestParams.put("date",time);
                    //requestParams.put("date","2016-04-08");
                   // Log.d("fengjw","DATA:"+userId+" "+companyId);

                    //url

                    httpService.postRequest(this, url, requestParams, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            if (s == null) {
                                Toast.makeText(context, "服务器内部错误", Toast.LENGTH_SHORT).show();
                            } else {
                                System.out.println(s);
                                Toast.makeText(context, "资源路径出错", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            try {
                                JSONObject jo = new JSONObject(s);

                                if (jo.getBoolean("result")) {

                                    JSONArray ja = jo.getJSONArray("data");
                                    //Log.d("fengjw","data:   "+ja.toString()) ;

                                    JSONObject entity1,entity2;

                                    if (ja != null && ja.length() > 0) {

                                        //1
                                            entity1 = ja.getJSONObject(0);
                                            String name1 = entity1.optString("qingJia");

                                           // Log.d("fengjw", "qingJia: " + entity1.optString("qingJia"));
                                            List<KaoqinLeaveData> kaoqinLeaveDataList = new ArrayList<>();

                                            JSONArray list1 = entity1.getJSONArray("list");
                                        if( list1.length() > 0) {
                                            for (int j = 0; j < list1.length(); j++) {
                                                KaoqinLeaveData  kaoqinLeaveData = new KaoqinLeaveData();
                                                JSONObject person1 = list1.getJSONObject(j);
                                                kaoqinLeaveData.setName(person1.getString("name"));
                                                kaoqinLeaveData.setHeadUrl(person1.getString("headUrl"));
                                                kaoqinLeaveData.setDepartment(person1.getString("department"));
                                               // Log.d("fengjw", "name1 : " + person1.getString("name"));
                                                kaoqinLeaveDataList.add(kaoqinLeaveData);
                                            }
                                        }
                                            Log.d("fengjw","kaoqinLeaveDataList :   "+kaoqinLeaveDataList.toString());

                                        //2
                                            entity2 = ja.getJSONObject(1);
                                            String name2 = entity2.optString("tiaoXiu");
                                           // Log.d("fengjw", "tiaoXiu: " + entity2.optString("tiaoXiu"));

                                            List<KaoqinTiaoxiuData> kaoqinTiaoxiuDataList = new ArrayList<KaoqinTiaoxiuData>();
                                            JSONArray list2 = entity2.optJSONArray("list");
                                        if( list2.length() > 0) {
                                            for (int j = 0; j < list2.length(); j++) {
                                                KaoqinTiaoxiuData kaoqinTiaoxiuData = new KaoqinTiaoxiuData();
                                                JSONObject person2 = list2.getJSONObject(j);
                                                kaoqinTiaoxiuData.setName(person2.getString("name"));
                                                kaoqinTiaoxiuData.setHeadUrl(person2.getString("headUrl"));
                                                kaoqinTiaoxiuData.setDepartment(person2.getString("department"));
                                               // Log.d("fengjw", "name : " + person2.getString("name"));
                                                kaoqinTiaoxiuDataList.add(kaoqinTiaoxiuData);
                                            }
                                        }
                                     //  Log.d("fengjw","0");
                                        lv = (ListView) findViewById(R.id.lv);
                                        listAdapterKaoqinTiaoxiu = new ListAdapterKaoqinTiaoxiu(NoSignKaoqinActivity.this);
                                      //  Log.d("fengjw","1");
                                        listAdapterKaoqinTiaoxiu.setData(name1, name2 , kaoqinLeaveDataList, kaoqinTiaoxiuDataList);
                                     //   Log.d("fengjw","2");
                                        listAdapterKaoqinTiaoxiu.notifyDataSetChanged();
                                        lv.setAdapter(listAdapterKaoqinTiaoxiu);

                                     //  Log.d("fengjw","3");

                                    }else {
                                        Toast.makeText(context, "暂无数据信息", Toast.LENGTH_SHORT).show();
                                    }
                                }else{
                                    Log.v("fengjw","no!");
                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                Toast.makeText(this, "网络不可用...", Toast.LENGTH_SHORT).show();
            }

        }
    }

    //JiaBan
    private void httpJiaBan(){
        if(datas.isEmpty()){

            HttpService httpService= HttpService.getInstance(this);
            if(NetUtils.hasNetwork(this)){
                try{

                    RequestParams requestParams=new RequestParams();
                    requestParams.put("companyId",companyId);
                    requestParams.put("userName",userId);


                    requestParams.put("date",time);
                    //requestParams.put("date","2016-04-08");
                 //   Log.d("fengjw","DATA:"+userId+" "+companyId);

                    //url

                    httpService.postRequest(this, url, requestParams, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            if (s == null) {
                                Toast.makeText(context, "服务器内部错误", Toast.LENGTH_SHORT).show();
                            } else {
                                System.out.println(s);
                                Toast.makeText(context, "资源路径出错", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            try {
                                JSONObject jo = new JSONObject(s);

                                if (jo.getBoolean("result")) {

                                    JSONArray ja = jo.getJSONArray("data");
                                    Log.d("fengjw","data:   "+ja.toString()) ;

                                    JSONObject entity1,entity2;

                                    if (ja != null && ja.length() > 0) {

                                        //1
                                        entity1 = ja.getJSONObject(0);
                                        String name1 = entity1.optString("jiaBan");

                                        Log.d("fengjw", "jiaBan: " + entity1.optString("jiaBan"));
                                        List<KaoqinLeaveData> kaoqinLeaveDataList = new ArrayList<>();

                                        JSONArray list1 = entity1.getJSONArray("list");
                                        if( list1.length() > 0) {
                                            for (int j = 0; j < list1.length(); j++) {
                                                KaoqinLeaveData  kaoqinLeaveData = new KaoqinLeaveData();
                                                JSONObject person1 = list1.getJSONObject(j);
                                                kaoqinLeaveData.setName(person1.getString("name"));
                                                kaoqinLeaveData.setHeadUrl(person1.getString("headUrl"));
                                                kaoqinLeaveData.setDepartment(person1.getString("department"));
                                                Log.d("fengjw", "name1 : " + person1.getString("name"));
                                                kaoqinLeaveDataList.add(kaoqinLeaveData);
                                            }
                                        }
                                        Log.d("fengjw","kaoqinLeaveDataList :   "+kaoqinLeaveDataList.toString());

                                        //2
                                        entity2 = ja.getJSONObject(1);
                                        String name2 = entity2.optString("zhiBan");
                                        Log.d("fengjw", "zhiBan: " + entity2.optString("zhiBan"));
                                        List<KaoqinTiaoxiuData> kaoqinTiaoxiuDataList = new ArrayList<>();

                                        JSONArray list2 = entity2.optJSONArray("list");
                                        if( list2.length() > 0) {
                                            for (int j = 0; j < list2.length(); j++) {
                                                KaoqinTiaoxiuData kaoqinTiaoxiuData = new KaoqinTiaoxiuData();
                                                JSONObject person2 = list2.getJSONObject(j);
                                                kaoqinTiaoxiuData.setName(person2.getString("name"));
                                                kaoqinTiaoxiuData.setHeadUrl(person2.getString("headUrl"));
                                                kaoqinTiaoxiuData.setDepartment(person2.getString("department"));
                                                kaoqinTiaoxiuDataList.add(kaoqinTiaoxiuData);
                                                Log.d("fengjw","List : "+ kaoqinTiaoxiuDataList.size() + "  "+ kaoqinTiaoxiuDataList.get(j).getName());
                                            }
                                        }
                                        Log.d("fengjw","0");
                                        lv = (ListView) findViewById(R.id.lv);
                                        listAdapterKaoqinTiaoxiu = new ListAdapterKaoqinTiaoxiu(NoSignKaoqinActivity.this);
                                        //Log.d("fengjw","1");
                                        listAdapterKaoqinTiaoxiu.setData(name1, name2 , kaoqinLeaveDataList, kaoqinTiaoxiuDataList);
                                        //Log.d("fengjw","2");
                                        listAdapterKaoqinTiaoxiu.notifyDataSetChanged();
                                        lv.setAdapter(listAdapterKaoqinTiaoxiu);

                                        //Log.d("fengjw","3");

                                    }else {
                                        Toast.makeText(context, "暂无数据信息", Toast.LENGTH_SHORT).show();
                                    }
                                }else{
                                    Log.v("fengjw","no!");
                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                Toast.makeText(this, "网络不可用...", Toast.LENGTH_SHORT).show();
            }

        }
    }




    private void initTitleBar(){
        centerView = (TextView) findViewById(R.id.titlebar_center_text);

        centerView.setText(title);
        //left
        ImageView leftView=(ImageView)findViewById(R.id.titlebar_left_img);
        leftView.setImageResource(R.drawable.ease_back);
        leftView.setOnClickListener(this);
        //right
        ImageView rightView=(ImageView)findViewById(R.id.titlebar_right_img);
        rightView.setVisibility(View.GONE);

//        TextView rightText=(TextView)findViewById(R.id.titlebar_right_tv);
//        rightText.setVisibility(View.VISIBLE);
//        rightText.setText(R.string.kaopin_update);

        titleBarView = (TitleBarView) findViewById(R.id.titleBar);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
    }

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.titlebar_left_img:
                finish();
                break;
            case R.id.kapqin_son_date_image:
                datePicker.show(getFragmentManager(), "hello");
                if(title.equals("缺勤记录"))
                    hpptNoSignIn();
                if (title.equals("请假/调休"))
                    httpTiaoXiu();
                if (title.equals("值班/加班"))
                    httpJiaBan();
                break;
        }
        //showPopupWindow(view);
    }
}
